package com.xiang.sql.service;

import java.util.List;
import java.util.ArrayList;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiang.api.Util;
import com.xiang.api.entity.Message;
import com.xiang.sql.StaticSql;
import com.xiang.sql.entity.Voucher;
import com.xiang.sql.entity.User;
import com.xiang.sql.mapper.VoucherMapper;

/**
 * 代金券 服务类
 * 
 * @author mac-xiang
 */
@Service
public class VoucherService extends ServiceImpl<VoucherMapper, Voucher> {
  @Resource
  VoucherMapper mapper;

  private QueryWrapper<Voucher> readWrapper(JSONObject p, User per, String prefix) {
    QueryWrapper<Voucher> ret = Util.getQuery(p, Voucher.class, prefix);
    if (Util.isEmpty(p.getString("id")) && per != null && !per.per("代金券创建")) {
      ret.last("LIMIT 0,0");
    }
    return ret;
  }

  private QueryWrapper<Voucher> readWrapper(JSONObject p, User per) {
    return readWrapper(p, per, "a");
  }

  private final static String limit = " LIMIT %d,%d";

  private List<Voucher> getList(QueryWrapper<Voucher> q) {
    List<Voucher> r = mapper.selectList2(q);
    if (r == null || r.size() == 0) {
      throw new RuntimeException("卡密错误");
    }
    return r;
  }

  private List<Voucher> getList(JSONObject p, User per) {
    return getList(readWrapper(p, per));
  }

  private Page<Voucher> getPage(Page<Voucher> page, JSONObject p, User per) {
    QueryWrapper<Voucher> q = readWrapper(p, per);
    page.setTotal(mapper.count2(q));
    final long c = page.getCurrent(), s = page.getSize();
    List<Voucher> d = getList(readWrapper(p, per).last(String.format(limit, s * (c - 1), s)));

    page.setRecords(d);
    return page;
  }

  public int create(JSONObject p, User per) {
    long time = Util.time();
    int sum = p.getIntValue("sum", 0), money = p.getIntValue("money", 0);
    String name = p.getString("name"), image = p.getString("image");
    if (per != null && sum > 0 && money > 0 && per.per("代金券创建")) {
      List<Voucher> ls = new ArrayList<>();
      for (int i = 0; i < sum; i++) {
        ls.add(new Voucher(time, per.id, name, money, image));
      }
      name = Util.insertSql(ls, Voucher.class);
      StaticSql.run.query(name);
      return sum;
    }
    throw new RuntimeException("没有权限");
  }

  public Object use(JSONObject p, User per) {
    Message ret = new Message();
    ret.type = "error";
    ret.message = "请先登录";
    Voucher entity = null;
    boolean use = true;
    if (!use) {
      ret.message = "未到使用时间";
    }
    if (use && per != null) {
      entity = this.getById(p.getString("id"));
      if (entity == null) {
        ret.message = "卡密错误";
      } else {
        ret.data = entity;
        if (Util.isEmpty(entity.use)) {
          ret.type = "success";
          ret.message = "兑付成功";
          // mapper.update(new UpdateWrapper<Voucher>().eq("id", entity.id).set("`use`",
          // per.id));
          long time = Util.time();
          StaticSql.run.safeQuery(String.format(
              "UPDATE `voucher` SET `change_time`=%d,`use`='%s' WHERE id='%s';UPDATE `user` SET `money`=`money`+%d WHERE id='%s';",
              time, per.id, entity.id, entity.money, per.id));
        } else {
          ret.message = "此卡已失效";
        }
      }
    }
    return ret;
  }

  public Object read(JSONObject p, User per) {
    Page<Voucher> page = Util.getPage(p, Voucher.class);
    return page == null ? getList(p, per) : getPage(page, p, per);
  }

  public int delete(JSONObject p, User per) {
    if (per != null && per.per("代金券删除")) {
      QueryWrapper<Voucher> q = Util.getQuery(p, Voucher.class);
      if (this.count(q) > 10) {
        throw new RuntimeException("删除数据的数量不能超过10条");
      }
      return mapper.delete(q);
    }
    throw new RuntimeException("没有权限");
  }

  public List<String> ids(JSONObject p, User per) {
    List<String> ret = new ArrayList<>();
    QueryWrapper<Voucher> qw = readWrapper(p, per, null).select("id");
    mapper.selectList(qw).forEach(e -> {
      ret.add(e.id);
    });
    return ret;
  }
}
